import { Controller, Post, Body, Request } from '@nestjs/common';
import { LoginService } from './login.service';
import { RegisterDto, LoginDto, ForgotDto } from './dto/login.dto';

@Controller('login')
export class LoginController {
  constructor(private readonly loginService: LoginService) { }

  @Post('login')
  login(@Body() body: LoginDto) {
    return this.loginService.login(body);
  }

  @Post('register')
  register(@Body() body: RegisterDto, @Request() req) {
    // 获取用户IP地址
    const userIp = this.getClientIp(req);
    return this.loginService.register(body, userIp);
  }

  @Post('forgot')
  forgot(@Body() body: ForgotDto) {
    return this.loginService.forgot(body);
  }

  /**
   * ? 获取客户端真实IP地址
   * ! 处理代理、负载均衡等场景
   */
  private getClientIp(req): string {
    // 尝试从各种代理头中获取真实IP
    const ip = req.headers['x-forwarded-for'] ||
      req.headers['x-real-ip'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      (req.connection.socket ? req.connection.socket.remoteAddress : null);

    // 如果是IPv6格式的本地地址，返回IPv4格式
    if (ip === '::1' || ip === '::ffff:127.0.0.1') {
      return '127.0.0.1';
    }

    // 如果x-forwarded-for包含多个IP（逗号分隔），取第一个
    if (typeof ip === 'string' && ip.includes(',')) {
      return ip.split(',')[0].trim();
    }

    return ip;
  }
}
